<template>
  <div class="login-container">
    <div class="login">
      <div class="title">后台管理系统</div>
      <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="loginForm.username" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" prefix-icon="el-icon-lock" v-model="loginForm.password" />
        </el-form-item>
        <div class="btns">
          <el-button type="primary" @click="vcodeVisible = true">登录</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
        </div>
      </el-form>
      <Vcode :show="vcodeVisible" @success="login" @close="vcodeVisible = false" />
    </div>
  </div>
</template>

<script>
import Vcode from 'vue-puzzle-vcode'

export default {
  name: 'Login',
  components: { Vcode },
  data() {
    return {
      // 登录表单对象
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 登录表单验证规则对象
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 之间', trigger: 'blur' }
        ]
      },
      // 控制验证框的显示与隐藏
      vcodeVisible: false
    }
  },
  methods: {
    // 登录
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/admin/login', this.loginForm)
        // 登录失败
        if (res.status !== 200) this.$message.error(res.msg)
        // 登录成功
        this.$message.success(res.msg)
        // 存储token到本地
        sessionStorage.setItem('token', res.token)
        // 跳转到后台首页
        this.$router.push('/home')
      })
    },
    // 重置表单的处理函数
    resetForm() {
      this.$refs.loginFormRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  height: 100%;
  background-color: #2b4b6b;

  .login {
    position: relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 450px;
    height: 300px;
    background-color: #fff;
    border-radius: 3px;
    padding: 20px;

    .title {
      font-size: 20px;
      text-align: center;
      line-height: 40px;
      margin-bottom: 40px;
    }

    .el-form {
      position: relative;
      bottom: 0;
      width: 100%;

      .btns {
        display: flex;
        justify-content: flex-end;
        margin-top: 30px;
      }
    }
  }
}
</style>
